package com.house.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import com.house.mapper.UserMapper;
import com.house.service.UserService;
import com.house.entity.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author asus
 * @since 2021-02-28
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 用户登录
     * @param user
     * @return
     */
    @Override
    public User login(User user) {
        String password = DigestUtil.md5Hex(user.getPassword());
        user.setPassword(password);
        user = userMapper.login(user);
        if(user == null)
        {
            return null;
        }
        else{
            System.out.println(user);
            return user;
        }
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Override
    public Integer register(User user) {
        String password = DigestUtil.md5Hex(user.getPassword());
        user.setPassword(password);

        if(userMapper.register(user) == 1)
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    @Override
    public User updateUserInfo(User user) {
        if(userMapper.updateUserInfo(user) == 1)
        {
            System.out.println(user);
            user = userMapper.getUserByUserNameOrId(user.getUsername(), null);
            return user;
        }
        return null;
    }

    /**
     * 修改密码
     * @param username
     * @param password1
     * @param password2
     * @return
     */
    @Override
    public boolean updatePassword(String username, String password1, String password2) {
        password1 = DigestUtil.md5Hex(password1);
        password2 = DigestUtil.md5Hex(password2);
        if (userMapper.updatePassword(username, password1, password2) == 1)
        {
            return true;
        }
        return false;
    }

    /**
     * 查找用户
     * @param type
     * @return
     */
    @Override
    public List<User> getAllUser(Integer type) {
        List<User> list = userMapper.getAllUser(type);
        if(list != null)
        {
            return list;
        }
        return null;
    }

    /**
     * 查询所有房间
     * @param username
     * @return
     */
    @Override
    public User getUserByUsernameOrId(String username, Integer id) {
        User user = userMapper.getUserByUserNameOrId(username, id);
        if(user != null)
        {
            return user;
        }
        return null;
    }

    @Override
    public Integer updateUserAvatar(String username, String avatar) {
        return userMapper.updateUserAvatar(username, avatar);
    }
}
